const moment = require('moment');
const path = require('path');
const fs = require('fs');
const jwt = require('jsonwebtoken');
const os = require('os');

const $config = require('../../config');

//获取本机IP
function getIPAdress() {
  const interfaces = os.networkInterfaces();
  for (let devName in interfaces) {
    let iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      let alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
}
module.exports = {
  config: {
    multipart:true,                 // 支持文件上传
    encoding:'gzip',
    formidable:{
      uploadDir: path.join(__dirname, '../../public/uploads'), // 设置文件上传目录
      keepExtensions: true,          // 保持文件的后缀
      maxFieldsSize:2 * 1024 * 1024, // 文件上传大小
      onFileBegin: (name,file) => {   // 文件上传前的设置
        console.log(`name: ${name}`);
        console.log('上传信息file', file);
      },
    }
  },  
  upload: async (ctx, next) => {
    const token = ctx.request.header.token;
    await jwt.verify(token, $config.tokenSecret, async (err, resultToken) => { // resultToken 解析token值
      if (err) {  //  时间失效的时候/ 伪造的token
        ctx.body = {
          success: false,
          result: '验证已过期！',
          ...err
        };
        return;
      }
      // 读取上传的图片信息
      const files = ctx.request.files;
      if (!files) {
        ctx.body = {
          success: false,
          message: '上传失败',
          result: '',
        };
        return;
      }
      const path = files.Upload.path.split('\\');
      const pathIndex = path.reverse().findIndex(item => item === 'public');
      const data = {
        originName:files.Upload.name,
        name:path[0],
        originUrl: path.reverse().join('/'),
        url: 'http://'+getIPAdress()+$config.servePort+'/'+path.slice(-pathIndex).join('/'),
      };
      ctx.body = {
        success: true,
        message: '上传成功',
        result: data,
      };
    })
  }
};
